package com.gcb.framework.web.service;

import com.gcb.common.constant.CacheConstants;
import com.gcb.common.constant.Constants;
import com.gcb.common.core.redis.RedisCache;
import com.gcb.common.enums.LoginType;
import com.gcb.common.exception.ServiceException;
import com.gcb.common.exception.user.*;
import com.gcb.common.utils.MessageUtils;
import com.gcb.common.utils.StringUtils;
import com.gcb.common.utils.ip.IpUtils;
import com.gcb.framework.manager.AsyncManager;
import com.gcb.framework.manager.factory.AsyncFactory;
import com.gcb.framework.model.AppLoginUser;
import com.gcb.framework.security.context.AuthenticationContextHolder;
import com.gcb.framework.security.custom.AppLoginAuthenticationToken;
import com.gcb.framework.security.custom.AppVerifyCodeLoginAuthToken;
import com.gcb.framework.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.regex.Pattern;

/**
 * App登录校验方法
 *
 * @author ruoyi
 */
@Component
public class AppLoginService {

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService configService;

    /**
     * 登录验证
     *
     * @param username  账号
     * @param password  密码
     * @param code      验证码
     * @param uuid      唯一标识
     * @param loginType 登录类型 0账号密码登录  1短信登录
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid, String loginType) {
        boolean isPassword = false;
        
        // 登录前置校验
        loginPreCheck(username, password);

        // 在判断是密码还是验证码登录 默认账号密码登录
        if (StringUtils.isBlank(loginType) || LoginType.ACCOUNT.getCode().equals(loginType)) {
            if (StringUtils.isBlank(password)){
                throw new ServiceException("用户密码不能为空");
            }
            // 图片验证码校验 APP 没有验证码
            // validateCaptcha(username, code, uuid);
            isPassword = true;
        } else if (LoginType.SMS.getCode().equals(loginType)) {
            // 短信验证码校验
            validateVerifyCode(username, code);
            // 验证码校验后 删除验证码
            String verifyKey = CacheConstants.APP_VERIFY_CODE_KEY + StringUtils.nvl(username, "");
            redisCache.deleteObject(verifyKey);
        } else {
            throw new ServiceException("请选择正确的登录方式");
        }

        // 生成token
         return loginCheckDetail(isPassword, username, password, loginType);
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * app端验证码登录-校验验证码
     * @param phone 电话
     * @param code 验证码
     * @return 结果
     */
    public void validateVerifyCode(String phone, String code) {
        if (!Pattern.compile("^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$").matcher(phone).matches()) {
            throw new ServiceException("手机号格式错误");
        }

        String verifyKey = CacheConstants.APP_VERIFY_CODE_KEY + StringUtils.nvl(phone, "");
        Long expireTime = redisCache.getExpire(verifyKey);
        if (expireTime != null && expireTime.longValue() > 0){
            String verifyCodeCache = redisCache.getCacheObject(verifyKey);
            if (StringUtils.isBlank(verifyCodeCache)){
                throw new ServiceException("系统错误，请重新发送验证码");
            }
            if (!code.equals(verifyCodeCache)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, MessageUtils.message("user.smscode.error")));
                throw new ServiceException("验证码错误");
            }
        } else {
            // 缓存过期
            throw new ServiceException("此验证码已过期，请重新发送验证码");
        }
    }

    /**
     * 登录校验
     * @param isPassword
     * @param username
     * @param password
     * @param loginType
     * @return
     */
    public String loginCheckDetail(boolean isPassword, String username, String password, String loginType) {
        Authentication authentication = null;
        try {
            if (isPassword) {
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
                AuthenticationContextHolder.setContext(authenticationToken);
                // 该方法会去调用 AppUserDetailsServiceImpl.loadUserByUsername
                authentication = authenticationManager.authenticate(new AppLoginAuthenticationToken(username));
            } else {
                AppVerifyCodeLoginAuthToken authenticationToken = new AppVerifyCodeLoginAuthToken(username);
                AuthenticationContextHolder.setContext(authenticationToken);

                // 该方法会去调用 AppVerifyCodeLoginServiceImpl.loadUserByUsername
                authentication = authenticationManager.authenticate(authenticationToken);
            }
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        AppLoginUser loginUser = (AppLoginUser) authentication.getPrincipal();
        loginUser.setLoginTime(System.currentTimeMillis());

        // 生成token
        return tokenService.createToken(loginUser);
    }

}
